package com.higgins.eventtracking.client.health.fundamentals;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.higgins.eventtracking.client.EventTrackingService;
import com.higgins.eventtracking.client.EventTrackingServiceAsync;
import com.higgins.eventtracking.client.dto.HealthAlertDTO;
import com.higgins.eventtracking.client.dto.TimeTableTaskDTO;
import com.higgins.eventtracking.client.genericcomponents.GenericColumn;
import com.higgins.eventtracking.client.genericcomponents.GenericColumns;
import com.higgins.eventtracking.client.genericcomponents.GenericTable;

public class WeeklyTimeTableTable extends GenericTable	{
	private static final Logger log = Logger.getLogger(WeeklyTimeTableTable.class.getName());
	private final EventTrackingServiceAsync greetingService = GWT
			.create(EventTrackingService.class);
	private Date storedDate = new Date();
	private Integer weekNow = null;
	
	public WeeklyTimeTableTable(GenericColumns genericColumns) {
		super(genericColumns);
		greetingService.getWeekNumber(new AsyncCallback<Integer>() {
			@Override
			public void onFailure(Throwable caught) {
				
			}

			@Override
			public void onSuccess(Integer result) {
				weekNow = result;
				refresh();
			} } );
//		listsLoaded();
	}
	public void listsLoaded()	{
		retrieveDTOs();
	}
	public void setDate(Date date)	{
		storedDate = date;
		if (weekNow!=null)
			refresh();
	}
	public void retrieveDTOs()	{
		greetingService.retrieveTimeTableTasks(false, false, true, false, false, storedDate, new AsyncCallback<List<TimeTableTaskDTO>>()  {
			@Override
			public void onFailure(Throwable caught) {
				log.info("WeeklyTimeTableTable: " + caught.toString());
			}

			@Override
			public void onSuccess(List<TimeTableTaskDTO> result) {
				loadData(convertDTOtoRowArray(result));
			}
		});		
	}
	private int getWeekNow()	{
		return weekNow;
	}
	private boolean todaysDate(Date dateParam)	{
		Date theDateRightNow = new Date();
		final DateTimeFormat dayFormat = DateTimeFormat.getFormat("d");
		final DateTimeFormat monthFormat = DateTimeFormat.getFormat("M");
		final DateTimeFormat yearFormat = DateTimeFormat.getFormat("y");
		final String nowDay = dayFormat.format(theDateRightNow);
		final String dateDay = dayFormat.format(dateParam);
		final String nowMonth = monthFormat.format(theDateRightNow);
		final String dateMonth = monthFormat.format(dateParam);
		final String nowYear = yearFormat.format(theDateRightNow);
		final String dateYear = yearFormat.format(dateParam);
		
		return nowDay.equals(dateDay) && nowMonth.equals(dateMonth) && nowYear.equals(dateYear);
	}
	private List<List<Object>> convertDTOtoRowArray(List<TimeTableTaskDTO> timeTableTaskDTOs)	{
		List<List<Object>> rows = new ArrayList<List<Object>>();
		int weekNow = todaysDate(storedDate)?getWeekNow():0;
		for (TimeTableTaskDTO dto:timeTableTaskDTOs)	{
			while (weekNow < dto.getWeek())	{
				List<Object> row = new ArrayList<Object>();
				row.add(null);
				row.add(weekNow);
				row.add("");
				row.add("");
				row.add("");
				row.add("");
				rows.add(row);				
				weekNow++;
			}
			List<Object> row = new ArrayList<Object>();
			row.add(dto.getId());
			row.add(dto.getWeek());
			row.add(dto.getTask()!=null?dto.getTask():"");
			row.add(dto.getTask2()!=null?dto.getTask2():"");
			row.add(dto.getTask3()!=null?dto.getTask3():"");
			row.add(dto.getTask4()!=null?dto.getTask4():"");
			rows.add(row);
			weekNow++;
		}
		while (weekNow <= 52)	{
			List<Object> row = new ArrayList<Object>();
			row.add(null);
			row.add(weekNow);
			row.add("");
			row.add("");
			row.add("");
			row.add("");
			rows.add(row);				
			weekNow++;
		}
		return rows;
	}
	protected void addObject(int row, int column, Object object)	{
		ensureRowAvailable(row);
		GenericColumn genericColumn = genericColumns.getColumn(column);
//		if (genericColumn.getType().equals(JobSiteDTO.class))	{
//			addJobSiteDTO(row, column, object, genericColumn);
	}
	
	public void updateItemCell(int row)	{
		TimeTableTaskDTO dto = new TimeTableTaskDTO();
		dto.setId(getId(row));
		dto.setWeek(getWeekFromText(getText(row, 1)));
        dto.setWeekYear(getYear(storedDate));
		dto.setTask(getText(row, 2));
		dto.setTask2(getText(row, 3));
		dto.setTask3(getText(row, 4));
		dto.setTask4(getText(row, 5));
		dto.setDate(storedDate);
		updateRow(dto);
	}
    private Integer getYear(Date date) {
        return 1900 + date.getYear();
    }
	
	private Integer getWeekFromText(String timeText)	{
//		if (timeText.contains(":"))	{
//			int location = timeText.indexOf(":");
//		String hourText = timeText.substring(0, location);
		String yearText = timeText;
		return Integer.parseInt(yearText);
//		}
//		return null;
	}
	private void updateRow(TimeTableTaskDTO dto)	{
		try {
			greetingService.updateTimeTableTask(dto, new AsyncCallback<String>()	{
					@Override
					public void onFailure(Throwable caught) {
						log.info("YearlyTimeTableTable: " + caught.toString());
					}

					@Override
					public void onSuccess(String result) {
						setRowIdAfterUpdate(result);
					}
				});
		} catch (IllegalArgumentException e) {
			log.info("HealthAlertTable: " + e.toString());
		} /*catch (SecurityAccessDeniedException e) {
			log.info("SecurityAccessDeniedException: " + e.toString());
		} 		*/
	}
}
